<?php
/* ******************************
 * INVOICE aJax actions
 * ******************************
 */
 
set_time_limit(0);

include('../../includes/classes/core.php');
include('../../includes/classes/invoice.class.php');
include('../../includes/classes/logger.class.php');

$service_url	= 'https://www.revenue.mof.ge/ntosservice/ntosservice.asmx?WSDL';
$action			= $_REQUEST['act'];
$client_id		= $_REQUEST['client_id'];
$error			= '';
$data			= '';
$properties 	= GetCompanyProperties();
$c_date 		= date('Y-m-d\TH:i:s');


$invoice	= new invoice($service_url, $properties['su'], $properties['sp'], $properties['rs_user_id'], $properties['un_id']);
$_log   	= Logger::instance('../../log/wsdl/wsdl/', Logger::OFF);

switch ($action) {	
	case 'create_invoice':
		$warehouse_ids		= json_decode( '['.$_REQUEST['wareHouseID'].']' );
		
		
		$invoice->set_invoice_id(0);
		$buyer_un_id = GetClientUnId($client_id);
		$result      = $invoice->create_invoice( $c_date, $buyer_un_id);
		
		if( $result['results'] ){
			$error = 'ანგარიშფაქტურა წარმატებით გაიგზავნა!';
			
			SaveInvoiceId($result['invoice_id'], $warehouse_ids);
			$invoice->set_invoice_id($result['invoice_id']);
			$array = AddServicesToInvoice($result['invoice_id']);
			
			for ($i = 0; $i < count($array); $i++) {
				$result =  $invoice->add_services_in_invoice($array[$i]['service'], $array[$i]['quantity'], $array[$i]['price']);
			}
			//$invoice->send_invoice();
		}else{
			$error = 'ანგარიშფაქტურა არ გაიგზავნა!';
		}
		break;	
	default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode( $data );


/* ******************************
 *	INVOICE Functions
 * ******************************
 */

function GetCompanyProperties()
{
	$res = mysql_fetch_assoc(mysql_query("SELECT 	`su`,
    											 	`sp`,
													`rs_user_id`,
													`un_id`
									      FROM 		`company_properties`"));
	return $res;
}

function GetClientUnId($client_id){
	$res = mysql_fetch_assoc(mysql_query("
											SELECT 	`client`.`rs_un_id` AS `id`
											FROM 	`client`
											WHERE 	`client`.`id` = '$client_id'"));
	return $res['id'];
	
}

function SaveInvoiceId($invoice_id, $warehouse_ids){
	foreach ($warehouse_ids as $warehouse_id){
		$res = mysql_fetch_array( mysql_query("	SELECT		`warehouse`.`a_letter_id` as `a_letter_id`,
															`warehouse`.`d_letter_id`	as `d_letter_id`
												FROM		`warehouse`
												WHERE		`warehouse`.`id` = '$warehouse_id'"));
		if($res['a_letter_id'] != ''){
			$a_letter_id = $res['a_letter_id'];
			mysql_query("	UPDATE 	`a_letter`
							SET		`a_letter`.`invoice_id` = '$invoice_id'
							WHERE	`a_letter`.`id` = '$a_letter_id' ");			
		}else if($res['d_letter_id'] != ''){
			$d_letter_id = $res['d_letter_id'];
			mysql_query("	UPDATE 	`d_letter`
							SET		`d_letter`.`invoice_id` = '$invoice_id'
							WHERE	`d_letter`.`id` = '$d_letter_id' ");
		}
	}
}

function AddServicesToInvoice($invoice_id) {
	
	$result = mysql_query("
							SELECT		CASE	WHEN `cartridge_parts_type`.`name` = 'ტონერი' THEN	'დამუხტვა'
												ELSE	CONCAT(`cartridge_parts_type`.`name`, 'ს შეცვლა') 
										END AS service,
										COUNT(`warehouse_producing`.`cartridge_part_id`) AS quantity,
										SUM(`cartridge_pricelist`.`price`) AS price			
							FROM       	`a_letter`
							LEFT JOIN   `client_objects` ON `a_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN   `client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN 	`warehouse` ON `a_letter`.`id` = `warehouse`.`a_letter_id`
							LEFT JOIN 	`warehouse_detail` ON `warehouse`.`id` = `warehouse_detail`.`warehouse_id`
							LEFT JOIN 	`warehouse_producing` ON `warehouse_detail`.`id` = `warehouse_producing`.`warehouse_detail_id`
							RIGHT JOIN  `cartridge_pricelist` ON client.id = `cartridge_pricelist`.`client_id` AND  `warehouse_producing`.`cartridge_part_id` = `cartridge_pricelist`.`parts_type` AND `cartridge_pricelist`.`production_id` = `warehouse_detail`.`prod_id`
							LEFT JOIN 	`cartridge_parts_type` ON `warehouse_producing`.`cartridge_part_id` = `cartridge_parts_type`.`id`
							WHERE      	`a_letter`.`invoice_id` = '$invoice_id' && `warehouse_detail`.`type` != 2 && `cartridge_pricelist`.`price` != 0
							GROUP BY 	`warehouse_producing`.`cartridge_part_id`
						");
	$array = array();
	while ($row = mysql_fetch_assoc($result)) {
		$array[] = array(
						"service" 	=> $row['service'],
						"quantity" 	=> $row['quantity'],
						"price"		=> $row['price']
						);
	}
	
	$result = mysql_query("	SELECT    	`printer_parts_type`.`name` AS service,
										COUNT(`warehouse_producing`.`printer_part_id`) AS quantity,
										SUM(`printer_pricelist`.`price`) AS price
							FROM       	`d_letter`
							LEFT JOIN   `client_objects` ON `d_letter`.`client_object_id` = `client_objects`.`id`
							LEFT JOIN   `client` ON `client`.`id` = `client_objects`.`client_id`
							LEFT JOIN 	`warehouse` ON `d_letter`.`id` = `warehouse`.`d_letter_id`
							LEFT JOIN 	`warehouse_detail` ON `warehouse`.`id` = `warehouse_detail`.`warehouse_id`
							LEFT JOIN 	`warehouse_producing` ON `warehouse_detail`.`id` = `warehouse_producing`.`warehouse_detail_id`
							RIGHT JOIN  `printer_pricelist` ON client.id = `printer_pricelist`.`client_id` AND  `warehouse_producing`.`printer_part_id` = `printer_pricelist`.`parts_type` AND `printer_pricelist`.`production_id` = `warehouse_detail`.`prod_id`
							LEFT JOIN 	`printer_parts_type` ON `warehouse_producing`.`printer_part_id` = `printer_parts_type`.`id`
							WHERE      	`d_letter`.`invoice_id` = '$invoice_id' && `warehouse_detail`.`type` != 2 && `printer_pricelist`.`price` != 0
							GROUP BY		`warehouse_producing`.`printer_part_id`");
	
	while ($row = mysql_fetch_assoc($result)) {
		$array[] = array(
				"service" 	=> $row['service'],
				"quantity" 	=> $row['quantity'],
				"price"		=> $row['price']
		);
	}
	
	return $array;
}
?>